package com.michael.ims.gateway.component;

import com.michael.common.ex.TokenInvaildException;
import com.michael.ims.gateway.common.AccessDenyException;
import com.michael.io.Error;
import com.michael.io.RespData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 全局异常捕获
 */
public class CustomerErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
    private static Logger log = LoggerFactory.getLogger(CustomerErrorWebExceptionHandler.class);
    @Autowired
    private MessageSource messageSource;

    public CustomerErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, applicationContext);
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return request -> Mono.just(request1 -> {
            RespData result = new RespData();

            Throwable ex = this.getError(request1);
            Error error = new Error();
            result.setError(error);
            if (ex instanceof TokenInvaildException) {
                return ServerResponse.status(HttpStatus.UNAUTHORIZED).build();
            } else if (ex instanceof AccessDenyException) {
                result.setStatus(RespData.ERROR);
                error.setMessage("无权限访问");
            } else {
                log.info("未知异常", ex);
                result.setStatus(RespData.ERROR);
                error.setMessage("未知异常");
                error.setDetails(ex.getMessage());
            }
            return ServerResponse.ok()
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(BodyInserters.fromObject(result));
        });
    }
}
